package com.ziyun.pop.mall.module.user.web;

import java.io.PrintWriter;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.service.common.model.PageParamDto;
import com.service.common.model.PageResult;
import com.service.common.protocol.ResultCode;
import com.service.order.api.PayService;
import com.service.order.constant.OrderResult;
import com.service.order.constant.PayType;
import com.service.order.exception.OrderException;
import com.service.order.model.pay.RechargeParamDto;
import com.service.ucenter.api.UserWalletService;
import com.service.ucenter.model.wallet.AdvanceRecordVO;
import com.service.utils.push.umeng.JsonResult;
import com.utility.StringUtils;
import com.ziyun.pop.mall.module.user.config.AdvanceConfig;

/**
 * 用户预存款记录Controller
 *
 * @author lvai 8.15
 */
@Controller
public class UserAdvanceController {
	private static Logger _log = LoggerFactory.getLogger(UserAdvanceController.class);
	private static final String MODEL = "/user/userAdvance";

	@Autowired
	private UserWalletService userWalletService;

	@Autowired
	private PayService payService;

	@Autowired
	private AdvanceConfig advanceConfig;

	protected String userAdvanceReturnUrl;

	protected String postUserAdvanceReturnUrl;

	@PostConstruct
	public void init() {
		this.userAdvanceReturnUrl = StringUtils.isBlank(advanceConfig.getUserAdvanceReturnUrl()) ? null
				: advanceConfig.getUserAdvanceReturnUrl();
		this.postUserAdvanceReturnUrl = StringUtils.isBlank(advanceConfig.getPostUserAdvanceReturnUrl()) ? null
				: advanceConfig.getPostUserAdvanceReturnUrl();
	}

	/* GET页面 */
	@GetMapping(MODEL + "/index.do")
	@ResponseBody
	public ModelAndView index(HttpServletRequest request, HttpServletResponse response) {
		ModelAndView view = new ModelAndView("/user/userAdvance/index.html");
		return view;
	}

	/* post 页面 */
	@PostMapping(MODEL + "/postIndex.do")
	@ResponseBody
	public ModelAndView postIndex() {
		ModelAndView view = new ModelAndView("/user/userAdvance/index.html");
		return view;
	}

	/**
	 * 获取用户预存款充值记录
	 * 
	 * @return
	 */
	@PostMapping(MODEL + "/listAdvanceRecord.json")
	@ResponseBody
	public JsonResult<Map<String, Object>> listAdvanceRecord(PageParamDto pageParamDto) {
		Map<String, Object> map = new HashMap<String, Object>();
		PageResult<AdvanceRecordVO> advanceRecordVOPage = userWalletService.listAdvanceRecord(pageParamDto).getData();
		map.put("advanceRecordVOPage", advanceRecordVOPage);
		return JsonResult.success(map);
	}

	/**
	 * 预付款充值页面
	 *
	 * @return
	 */
	@GetMapping(MODEL + "/topUp.do")
	@ResponseBody
	public ModelAndView topUp() {
		ModelAndView view = new ModelAndView("/user/userAdvance/umfTopUp.html");
		return view;
	}

	/**
	 * 预存款充值
	 * 
	 * @return
	 * @throws Exception
	 */
	@GetMapping(MODEL + "/topUpPay.do")
	public ModelAndView topUpPay(HttpServletRequest request, HttpServletResponse response) throws Exception {
		RechargeParamDto payParamDto = new RechargeParamDto();
		String payType = request.getParameter("payType");
		String rechargeAmount = request.getParameter("rechargeAmount");
		payParamDto.setRechargeAmount(new BigDecimal(rechargeAmount));
		payParamDto.setPayType(PayType.valueOf(payType));
		String returnUrl = null;
		if (payParamDto.getPayType() != null) {
			switch (payParamDto.getPayType()) {
			case alipay:
			case weixin:
				returnUrl = this.userAdvanceReturnUrl;
				break;
			case upacppc:
			case umfalipay:
			case umfweixinpay:
			case umfupacppay:
				returnUrl = this.postUserAdvanceReturnUrl;
				break;
			default:
				throw new OrderException(ResultCode.PARAM_ERROR);
			}
		}
		payParamDto.setRetUrl(returnUrl);
		OrderResult<?> orderResult = payService.getRecharge(payParamDto);
		if (payParamDto.getPayType() != null) {
			Map<String, Object> map;
			switch (payParamDto.getPayType()) {
			case alipay:
			case upacppc:
				map = (Map<String, Object>) orderResult.getData();
				String html = (String) map.get("payUrl");
				response.reset();
				response.setHeader("Content-Type", "application/x-json; charset=UTF-8");
				response.setCharacterEncoding("utf-8"); // 解决Json数据传递中文乱码
				response.setContentType("text/html;charset=utf-8");
				PrintWriter out = response.getWriter();
				out.println(html);
				out.flush();
				out.close();
				break;
			case weixin:
				map = (Map<String, Object>) orderResult.getData();
				String code_url = (String) map.get("code_url");
				return new ModelAndView("redirect:/user/userAdvance/topUpWeixinPay.do？code_url=" + code_url
						+ "&&rechargeAmount=" + rechargeAmount);
			case umfalipay:
			case umfweixinpay:
			case umfupacppay:
				map = (Map<String, Object>) orderResult.getData();
				String payUrl = (String) map.get("payUrl");
				return new ModelAndView("redirect:" + payUrl);
			default:
				throw new OrderException(ResultCode.PARAM_ERROR);
			}
		}
		return null;
	}

	/**
	 * 微信充值
	 * 
	 * @return
	 * @throws Exception
	 */
	@GetMapping(MODEL + "/topUpWeixinPay.do")
	@ResponseBody
	public ModelAndView topUpWeixinPay(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String code_url = request.getParameter("code_url");
		String rechargeAmount = request.getParameter("rechargeAmount");
		ModelAndView view = new ModelAndView("/user/userAdvance/weixinPay.html");
		view.addObject("code_url", code_url);
		view.addObject("rechargeAmount", rechargeAmount);
		return view;
	}

	// /**
	// * 支付完成同步回调地址
	// *
	// * @param orderId
	// * @return
	// * @throws IOException
	// */
	// @GetMapping(MODEL + "/topUpSucess")
	// public ModelAndView topUpSucess(HttpServletRequest request,
	// HttpServletResponse response) throws IOException {
	// ModelAndView view = new ModelAndView("/user/userAdvance/paymentSucess.html");
	// return view;
	// }

	// @PostMapping(MODEL + "/excel/export.json")
	// @ResponseBody
	// public JsonResult<String> export(HttpServletResponse response) {
	// String excelTemplate =
	// "excelTemplates/user/userAdvance/user_advance_template.xls";
	// PageParamDto pageParamDto = new PageParamDto();
	// List<AdvanceRecordVO> advanceRecordVOList =
	// userWalletService.listAdvanceRecord(pageParamDto).getData()
	// .getRows();
	// try (InputStream is =
	// Thread.currentThread().getContextClassLoader().getResourceAsStream(excelTemplate))
	// {
	// // if (is == null) {
	// // throw new PlatformException("模板资源不存在：" + excelTemplate);
	// // }
	// // FileItem item = fileService.createFileTemp("user_advance.xls");
	// // OutputStream os = item.openOutpuStream();
	// // Context context = new Context();
	// // context.putVar("advanceRecordVOList", advanceRecordVOList);
	// // JxlsHelper.getInstance().processTemplate(is, os, context);
	// // // 下载参考FileSystemContorller
	// // return JsonResult.success(item.getPath());
	// } catch (IOException e) {
	// // throw new PlatformException(e.getMessage());
	// }
	// }

	// @PostMapping(MODEL + "/excel/export.json")
	// @Function("user.export")
	// @ResponseBody
	// public JsonResult<String> export(HttpServletResponse response,
	// UserAdvanceQuery condtion) {
	// String excelTemplate =
	// "excelTemplates/user/userAdvance/user_advance_template.xls";
	// condtion.setMemberId(corePlatformService.getCurrentOrg().getId().intValue());
	// PageQuery<UserAdvance> page = condtion.getPageQuery();
	// // 取出全部符合条件的
	// page.setPageSize(Integer.MAX_VALUE);
	// page.setPageNumber(1);
	// page.setTotalRow(Integer.MAX_VALUE);
	// List<UserAdvanceExcelExportData> userAdvances =
	// userAdvanceService.queryExcel(page);
	// try (InputStream is =
	// Thread.currentThread().getContextClassLoader().getResourceAsStream(excelTemplate))
	// {
	// if (is == null) {
	// throw new PlatformException("模板资源不存在：" + excelTemplate);
	// }
	// FileItem item = fileService.createFileTemp("user_advance.xls");
	// OutputStream os = item.openOutpuStream();
	// Context context = new Context();
	// context.putVar("userAdvances", userAdvances);
	// JxlsHelper.getInstance().processTemplate(is, os, context);
	// // 下载参考FileSystemContorller
	// return JsonResult.success(item.getPath());
	// } catch (IOException e) {
	// throw new PlatformException(e.getMessage());
	// }
	//
	// }
	//

	//
	// /**
	// * 预存款充值支付流程
	// *
	// * @param request
	// * @param response
	// * @return
	// */
	// @PostMapping(MODEL + "/topUpPay.json")
	// @Function("popUserTax.query")
	// @ResponseBody
	// public JsonResult<Map<String, Object>> topUpPay(HttpServletRequest request,
	// HttpServletResponse response) {
	// String payData = request.getParameter("payData");
	// Map paramValueMap = JsonUtils.string2Map(payData);
	// String payType = (String) paramValueMap.get("payType");
	// String bankCode = (String) paramValueMap.get("bankCode");
	// BigDecimal amount = BigDecimal.valueOf(Double.parseDouble((String)
	// paramValueMap.get("amount")));
	// PcRechargeParamDto pcRechargeParamDto = new PcRechargeParamDto();
	// pcRechargeParamDto.setPayment(PayType.valueOf(payType));
	// pcRechargeParamDto.setAmount(amount);
	// if (!StringUtils.isBlank(bankCode)) {
	// pcRechargeParamDto.setBankCode(BankCode.valueOf(bankCode));
	// }
	// Map<String, Object> map = new HashMap<String, Object>();
	// try {
	// map = userAdvanceService.getPcRechargePay(pcRechargeParamDto);
	// } catch (OrderException e) {
	// String message = e.getResultCode().getMessage();
	// return JsonResult.failMessage(message);
	// } catch (Exception e) {
	// System.out.println(e.getMessage());
	// return JsonResult.failMessage("支付失败");// 返回错误消息
	// }
	// return JsonResult.success(map);
	// }
	//
	// @GetMapping(MODEL + "/topUpPayFalseCallback.do")
	// @ResponseBody
	// public ModelAndView topUpPayFalseCallback(HttpServletRequest request,
	// HttpServletResponse response)
	// throws Exception {
	// String falseMsg = request.getParameter("falseMsg");
	// ModelAndView view = new ModelAndView("/user/userAdvance/payFalse.html");
	// view.addObject("falseMsg", falseMsg);
	// return view;
	// }
	//
	// /***
	// * 充值回调
	// *
	// * @param request
	// * @param response
	// * @return
	// * @throws Exception
	// */
	// @GetMapping(MODEL + "/umfAdvanceCallback.do")
	// @ApiOperation(value = "联动充值回调", notes = "联动充值回调")
	// @ResponseBody
	// public void umfAdvanceCallback(HttpServletRequest request,
	// HttpServletResponse response) throws Exception {
	// // 获取联动发送请求的参数
	// String requestParam = request.getQueryString();
	// System.out.println("请求参数 :" + requestParam);
	// // 调用异步通知解析方法
	// BaseResult<PayRecallResult> payResult =
	// recallService.payRecall(requestParam);
	// if (payResult.getCode() == ResultCode.SUCCESS.getCode()) {
	// PayRecallResult payRecallResult = payResult.getData();
	// // 交易状态
	// Boolean flag = userAdvanceService.rechargeCallBack(payRecallResult);
	// if (flag) {
	// response.setContentType("text/html;charset=utf-8");
	// PrintWriter out = response.getWriter();
	// out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01
	// Transitional//EN\">");
	// out.println("<HTML>");
	// out.println(" <HEAD><META NAME=\"MobilePayPlatform\" CONTENT=\"" +
	// payRecallResult.getResMetaData()
	// + "\" /></HEAD>");
	// out.println(" <BODY>");
	// out.print(" This is ");
	// out.print(this.getClass());
	// out.println(", using the GET method");
	// out.println("</BODY>");
	// out.println("</HTML>");
	// out.flush();
	// out.close();
	// }
	// }
	//
	// }

}
